use chrono::Local;
use serde::Deserialize;

use crate::{model, utils, Result};

#[derive(Deserialize)]
pub struct Update {
    pub content: String,
    pub is_md: bool,
    pub has_view_pwd: bool,
    pub view_pwd: String,
    pub has_man_pwd: bool,
    pub man_pwd: String,
}
impl Update {
    pub fn view_pwd(&self) -> Result<String> {
        if !self.has_view_pwd || self.view_pwd.is_empty() {
            return Ok("".to_string());
        }
        utils::hash_pwd(&self.view_pwd)
    }

    pub fn man_pwd(&self) -> Result<String> {
        if !self.has_man_pwd || self.man_pwd.is_empty() {
            return Ok("".to_string());
        }
        utils::hash_pwd(&self.man_pwd)
    }
}

impl Into<model::Note> for Update {
    fn into(self) -> model::Note {
        model::Note {
            content: self.content.clone(),
            is_md: self.is_md,
            has_view_pwd: self.has_view_pwd,
            view_pwd: self.view_pwd().unwrap_or_default(),
            has_man_pwd: self.has_man_pwd,
            man_pwd: self.man_pwd().unwrap_or_default(),
            is_arch: false,
            dateline: Local::now(),
            ..Default::default()
        }
    }
}
